﻿Public Class ActivityExplorer
    Inherits ExplorerTreeList

    Public imExplorer As CommonExt.Utils.ExplorerNodeInfo


    Private lastXxDays As Integer? = Nothing
    Private fromCrtDt As String = Nothing
    Protected EditPanePL As PLBase


    Public Sub New(ByVal aQueryName As String)
        MyBase.New(aQueryName)
        'AddHandler InitTreeActionOptionList, AddressOf Init_TreeActionOptionList
    End Sub

    Public Sub New()
        MyBase.New()
        'AddHandler InitTreeActionOptionList, AddressOf Init_TreeActionOptionList
    End Sub
    ''' <summary>
    ''' La sécurity par GCCT:
    ''' La meta query qui est recu est une 'ROOT' alors nous n'avons aucun data a filtrer.
    ''' une fois que nous avons le résultats de GetChildDisplayQuery()
    ''' nous connaissons chaqu'une des sous query qui seront en Format Explorer.
    ''' A ce moment on dois avoir un champ qui nous permet de relier chauqe query avec son dictionairre de GCCT.
    ''' la function da appman nous serviras a chercher les GCCT value accessble par user .
    ''' clea sera un string de format sql qui sera concatainner avec un .addsqlwhereor , méthode du pl.
    ''' </summary>
    ''' <remarks></remarks>
    Public Overrides Sub MergeMetaQueryResult()
        Dim aChildQueryToDisplay As DataTable = Nothing
        Dim aChildMQ As MetaQuery = Nothing
        MainMetaQuery = MetaQuery.GetMetaQueryByName(QueryName)
        MainMetaQuery.FillResultQuery()
        Dim aSqlWhere As String = String.Empty
        Dim aGCCTSWhere As String
        DataSrc = MainMetaQuery.ResultQuery
        Try
            aChildQueryToDisplay = MainMetaQuery.GetChildDisplayQuery()
            If aChildQueryToDisplay IsNot Nothing Then
                'Boucle de filtrage dimention et security
                For Each row As DataRow In aChildQueryToDisplay.Rows
                    aChildMQ = MetaQuery.GetMetaQueryByName(row("QueryName").ToString)
                    If aChildMQ IsNot Nothing Then
                        If Not String.IsNullOrEmpty(fromCrtDt) Then
                            aSqlWhere = String.Format("{0}.Crtd_DT >= '{1}'", aChildMQ.UniqueTable, fromCrtDt)
                        End If  'determiner  quoi aller cherché .
                        ' AppManager.GetGCCTSSecurity
                        aGCCTSWhere = GCCTFilter(row("QuerieCD").ToString()) 'MQ Code
                        If Not String.IsNullOrEmpty(aGCCTSWhere) Then

                        End If
                        If Not String.IsNullOrEmpty(aSqlWhere) AndAlso Not String.IsNullOrEmpty(aGCCTSWhere) Then
                            aChildMQ.SQLWhereContext = String.Format("{0} OR ({1} )", aSqlWhere, aGCCTSWhere)
                        Else
                            aChildMQ.SQLWhereContext = aSqlWhere & aGCCTSWhere
                        End If
                        'testpoint: Check Sqlstatement to verify user access on GCCTS
                        aChildMQ.FillResultQuery()

                        If aChildMQ.ResultQuery.Rows.Count > 0 Then
                            DataSrc.Merge(aChildMQ.ResultQuery, False, MissingSchemaAction.Ignore)
                        End If
                    End If
                Next
            End If
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
    End Sub

    Public Function GCCTFilter(ByVal MQCode As String) As String
        Dim aGCCTSFilter As String = String.Empty
        Dim aGCCTList As String = String.Empty
        Dim GCCTSID As KeyValuePair(Of String, System.Guid)
        Dim DictObj As New Dictionary(Of String, System.Guid)

        Using dataView As DataView = AppManager.GetControlSecurity(MQCode, "METAQ")
            If dataView IsNot Nothing AndAlso dataView.Count > 0 Then
                dataView.RowFilter = "Property = 'GCCTSList'"
                If dataView.Count > 0 Then
                    aGCCTList = dataView.Item(0).Row("Value").ToString()
                End If
            End If

            Select Case aGCCTList
                Case "ProjectGCCTS"
                    DictObj = IdRepository.ProjectGCCTS
                Case "InventoryBatchGCCTS"
                    DictObj = IdRepository.InventoryBatchGCCTS
            End Select
        End Using
        Dim emptyguid As Boolean
        Dim aGetGCCTGUID As String
        For Each GCCTSID In DictObj

            aGetGCCTGUID = AppManager.GetGCCTSSecurity(IdRepository.ALLOWREAD, GCCTSID.Value, emptyguid)
            If Not emptyguid Then
                If Not String.IsNullOrEmpty(aGCCTSFilter) Then
                    aGCCTSFilter += String.Format(" AND ({0} IS NULL OR {0} IN ({1}) )  ", GCCTSID.Key, aGetGCCTGUID)
                Else
                    aGCCTSFilter += String.Format(" ({0} IS NULL OR {0} IN ({1}) )  ", GCCTSID.Key, aGetGCCTGUID)

                End If

            End If
        Next

        Return aGCCTSFilter
    End Function


    Public Overrides Sub PopulateDetailSection()
        Me.Cursor = Cursors.WaitCursor
        '
        If aGridControl IsNot Nothing Then
            aGridControl.Dispose()
            aGridControl = Nothing
        End If
        '
        Dim guidEnfant As Guid
        Dim aPLName As String

        Dim aPaneMetaQueryName As String
        Dim Ametaquerie As MetaQuery
        Dim frmCaption As String = "Activity"
        'DeskTopManager.GetMessage("CONNECT")

        Try
            guidEnfant = DirectCast(NodeDataRow(Me.KeyFieldName), Guid)
            aPLName = DirectCast(NodeDataRow("PL"), String)
            'imExplorer = New CommonExt.Utils.ThisIMExplorer(NodeDataRow)


            aPaneMetaQueryName = DirectCast(NodeDataRow("MetaQuerie"), String)
            Ametaquerie = MetaQuery.GetMetaQueryByName(aPaneMetaQueryName)

            'c<est ici qu<on bind les info du noeud qui articule le Edit PANE
            EditPanePL = PLBase.CreateInstanceOf(aPLName, aPaneMetaQueryName)
            EditPanePL.SQLWhere = String.Format("ProjectClassID_FK IN ({0})", AppManager.GetGCCTSSecurity(IdRepository.ALLOWREAD, IdRepository.APP_PROJECTCLASS))


            aGridControl = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = EditPanePL, .SecureGrid = True, .Name = Ametaquerie.Caption, .FormCtrlCD = MyBase.PanelName}
            If Not Guid.Empty.Equals(guidEnfant) Then
                EditPanePL.SQLWhere = String.Format("{0} = '{1}'", Ametaquerie.GUIDField, guidEnfant)
                If NodeDataRow.Table.Columns.Contains("CODE") AndAlso NodeDataRow.Table.Columns.Contains("Description") Then
                    frmCaption = String.Format("{0} {1}", NodeDataRow("CODE"), NodeDataRow("Description"))
                Else
                    frmCaption = "Code, Description"
                End If
            End If


            Select Case Focus()
                Case 0
                    AddHandler aGridControl.InitNewMasterRow, AddressOf InitNewActivity
                    AddHandler aGridControl.AfterInitView, AddressOf AfterInitView
                    AddHandler aGridControl.MasterCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
                    AddHandler aGridControl.DetailCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
                    AddHandler aGridControl.MasterRowNotify, AddressOf RowNotify
                    AddHandler aGridControl.ValidateMasterRow, AddressOf ValidateRow
                    'Appelle Dynamique du Menu Action (ContextMenu)
                    AddHandler aGridControl.InitGridActionOptionList, AddressOf Init_GridActionOptionList
                Case Else
                    aGridControl.ExpandFirstMasterRow = True
                    AddHandler aGridControl.AfterInitView, AddressOf AfterInitView
                    AddHandler aGridControl.MasterCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
                    AddHandler aGridControl.DetailCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
                    'AddHandler aGridControl.ShownDetailEditor, AddressOf ShownDetailEditor
                    AddHandler aGridControl.MasterRowNotify, AddressOf RowNotify
                    AddHandler aGridControl.ProcessCurrentDetailRecord, AddressOf ProcessCurrentRecord
                    AddHandler aGridControl.ValidateDetailRow, AddressOf ValidateRow
                    AddHandler aGridControl.ValidateMasterRow, AddressOf ValidateRow
                    'Appelle Dynamique du Menu Action (ContextMenu)
                    AddHandler aGridControl.InitGridActionOptionList, AddressOf Init_GridActionOptionList
            End Select



        Catch ex As Exception
            MessageWindow.ShowMessage(ex)

        End Try
        '
        'On trouve la form pour effacer les controle dedans et ensuite remettre le bon.
        'Comme ca on change le Detail selon la ligne dans L'explorer
        For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
            If aFrm.Name = PanelName Then
                aFrm.Controls.Clear()
                aFrm.Controls.Add(aGridControl)
                aFrm.Text = frmCaption
                aFrm.Show()
                aFrm.Focus()
            End If
            aFrm.Refresh()
        Next
        Me.Cursor = Cursors.Default
    End Sub

    Public Overridable Sub ShowActivityList()
        'ActivityPL = PLBase.CreateInstanceOf(PLTypeOf.Project_PL, "ActivityNoChild")
        ''Scoper nouveau PL en haut en haut        
        'aGridControl = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = ActivityPL, .SecureGrid = True, .Name = "Activity List", .FormCtrlCD = Nothing}
        'AddHandler aGridControl.AfterInitView, AddressOf AfterInitView
        'AddHandler aGridControl.MasterCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
        'AddHandler aGridControl.DetailCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
        ''AddHandler aGridControl.ShownDetailEditor, AddressOf ShownDetailEditor
        'AddHandler aGridControl.MasterRowNotify, AddressOf RowNotify
        'AddHandler aGridControl.ValidateMasterRow, AddressOf ValidateRow
    End Sub

    Public Overridable Sub ShowByActivity(ByVal activityID As System.Guid)
        'ActivityPL = PLBase.CreateInstanceOf(PLTypeOf.Project_PL, "Activity")
        'aGridControl = New GridExtPL() With {.Dock = DockStyle.Fill, .Pl = ActivityPL, .SecureGrid = True, .Name = "Activities", .FormCtrlCD = MyBase.PanelName}
        'ActivityPL.SQLWhere = String.Format("ProjectID = '{0}'", activityID)
        'aGridControl.ExpandFirstMasterRow = True
        'AddHandler aGridControl.AfterInitView, AddressOf AfterInitView
        'AddHandler aGridControl.MasterCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
        'AddHandler aGridControl.DetailCustomRowCellEditForEditing, AddressOf CustomRowCellEditForEditing
        ''AddHandler aGridControl.ShownDetailEditor, AddressOf ShownDetailEditor
        'AddHandler aGridControl.MasterRowNotify, AddressOf RowNotify
        'AddHandler aGridControl.ProcessCurrentDetailRecord, AddressOf ProcessCurrentRecord
        'AddHandler aGridControl.ValidateDetailRow, AddressOf ValidateRow
        'AddHandler aGridControl.ValidateMasterRow, AddressOf ValidateRow

    End Sub

    Private Sub Activity_GridLayout()
        Try

            Me.Cursor = Cursors.WaitCursor

            PL = New SystemBoxSDK.PL.CRMSDK.Project_PL("Activity")
            aGridLayout = New GridLayoutPL() With {.Dock = DockStyle.Fill, .Pl = PL, .FormCtrlCD = Nothing}

            For Each aFrm As XtraForm In Me.ParentForm.MdiChildren
                If aFrm.Name = PanelName Then
                    aFrm.Controls.Clear()
                    aFrm.Controls.Add(aGridLayout)
                    aFrm.Text = aGridLayout.Pl.QueryName
                    aFrm.Show()
                End If
                aFrm.Refresh()
            Next

            AddHandler aGridLayout.InitNewMasterRow, AddressOf InitNewLayoutRow

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        End Try
    End Sub



    Private Sub ActivityExplorer_Load(sender As Object, e As EventArgs) Handles Me.Load
        TreeActionOptionListLoad()
        MetaControlTreeListActionOptionList.ApplySecurity()
    End Sub
End Class
